/*
   @Copyright:LeetCode
   @Author:   tjyemail
   @Problem:  http://leetcode.com/problems/insertion-sort-list
   @Language: C++
   @Datetime: 19-11-19 19:11
   */

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
	ListNode* insertionSortList(ListNode* head) {
		ListNode *p, *q, H(-1);
		for(; head;){
			for(p=&H; (q=p->next) && q->val<=head->val; p=p->next);
			p=p->next=head;
			head=head->next;
			p->next=q;
		}
		return H.next;
	}
};
